﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {

        protected void Application_AuthenticateRequest(Object sender,
                                               EventArgs e)
        {

        }

        //protected void Application_AuthenticateRequest(object sender, EventArgs e)
        //{
        //    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        //    if (null == authCookie)
        //    {//There is no authentication cookie.
        //        Debug.WriteLine("Don't know you, dude.");
        //    }
        //    else
        //        Debug.WriteLine("Enjoy the party!");
        //}

        //private void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
        //{
        //    if (args.User != null)
        //    {
        //        var principalManager = ObjectFactory.GetInstance<IPatientSafetyPrincipalManager>();
        //        var principal = principalManager.SetPrincipal(args.User.Identity.Name);
        //        args.User = principal;
        //    }
        //}

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.ico/{*pathInfo}");
            routes.IgnoreRoute("scripts/{*pathInfo}");

            //routes.MapRoute(
            //  "SleepStudySearch",
            //  "{controller}/{action}/{status}",                           // URL with parameters
            //  new { status = "all" },  // Parameter defaults
            //  new { controller = @"SleepStudy", action = @"List" }
            //);


            //routes.MapRoute(
            //    "Basic",                                              // Route name
            //    "{controller}/{action}/{id}",                           // URL with parameters
            //    new { controller = "SleepStudy", action = "MainListing", id = "" }  // Parameter defaults
            //);
            routes.MapRoute("Default",
                                "{controller}/{action}/{id}",
                                new { controller = "PFSync", action = "DefaultView", id = "" }
                           );

        }

        protected void Application_Start()
        {
            Console.WriteLine("Application_Start()");
            RegisterRoutes(RouteTable.Routes);
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            Console.WriteLine("Application_Start(object, EventArgs)");
            RegisterRoutes(RouteTable.Routes);
        }

        public void Application_End(object sender, EventArgs e)
        {
            Console.WriteLine("Application_End");
            //  Code that runs on application shutdown

        }

        public void Application_Error(object sender, EventArgs e)
        {
            if (bool.Parse(System.Configuration.ConfigurationManager.AppSettings["SendEmail"]))
            {
                try
                {
                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                    StringBuilder body = new StringBuilder();
                    body.Append("Error on " + "" + Request.RawUrl + "\n");
                    Exception objErr = Server.GetLastError().GetBaseException();
                    body.Append(objErr.ToString());
                    var trace = new System.Diagnostics.StackTrace();
                    System.Exception ex = new System.Exception();
                    body.Append(objErr.TargetSite.ToString() + "<br />");
                    body.Append(objErr.Source.ToString() + "<br />");
                    if (objErr.InnerException != null)
                    {
                        body.Append(objErr.InnerException.ToString() + "<br />");
                    }
                    body.Append(trace);
                    if (null != System.Web.HttpContext.Current.Session)
                    {
                        foreach (string SessionVar in Session.Keys)
                        {
                            body.Append("<br />" + Session[SessionVar].ToString() + "\n");
                            System.Reflection.PropertyInfo[] props = Session[SessionVar].GetType().GetProperties();

                            body.AppendLine("======= START OBJECT =======");
                            foreach (System.Reflection.PropertyInfo pi in props)
                            {
                                body.AppendFormat(Session[SessionVar].ToString() + ".{0}:{1}\n", pi.Name, pi.GetValue(Session[SessionVar], null));

                            }
                            body.AppendLine("=======  END OBJECT  =======");

                        }
                    }

                    //Type sessionuser = Type.GetType(s);
                    HttpApplication application = (HttpApplication)sender;
                    HttpContext context = application.Context;

                    body.Append(application.ToString() + "" + "\n" + context.AllErrors.ToString());
                    body.Append("\n \n PatientFusionSync has been contacted.");
                    //TODO::        
                    //dump everything that is on the session in to a message body.
                    //also dump everything that is in the Application scope...but watch out for large files (dont write them in here... name and size only).
                    //also need to show the user a system error message/page and tell them support has been contacted.

                    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["supportEmail"], System.Configuration.ConfigurationManager.AppSettings["supportEmailProxy"], "Exception in Patient Safety Web Application", body.ToString());
                    smtp.Send(message);
                }
                catch (Exception ex)
                {
                    if (!System.Diagnostics.EventLog.SourceExists("ThreadException"))
                    {
                        System.Diagnostics.EventLog.CreateEventSource("ThreadException", "Application");
                    }

                    // Create an EventLog instance and assign its source.
                    System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
                    myLog.Source = "ThreadException";
                    myLog.WriteEntry(ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
                }
            }

        }

        public void Session_Start(object sender, EventArgs e)
        {
            Console.WriteLine("Session_Start");
            // Code that runs when a new session is started

        }

        public void Session_End(object sender, EventArgs e)
        {
            Console.WriteLine("Session_End");
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }